package com.winit.common.util;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;

/**
 * 解析xml文件
 * Created by wangjian on 16/10/9.
 */
public class Dom4jUtil {

    private static Logger logger = LoggerFactory.getLogger(Dom4jUtil.class);

    /**
     * 解析xml文件
     * @param xmlFilePath xml文件路径
     * @return
     */
    public static List<Element> parserXml(String xmlFilePath) throws Exception{
        List<Element> list = null;
        if(StringUtils.isEmpty(xmlFilePath)){
            logger.error("com.winit.common.util.Dom4jUtil.parserXml 参数为空");
            throw new Exception("解析xml文件,参数为空!");
        }
        File file = new File(xmlFilePath);
        if(!file.exists()){
            logger.error("com.winit.common.util.Dom4jUtil.parserXml 文件不存在。xmlFilePath="+xmlFilePath);
            throw new Exception("解析xml文件,文件不存在!path="+xmlFilePath);
        }

        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(file);
            Element root = document.getRootElement();
            list = root.elements();
        } catch (DocumentException e) {
            logger.error("com.winit.common.util.Dom4jUtil.parserXml 异常。xmlFilePath="+xmlFilePath,e);
            throw new Exception("解析xml文件异常!path="+xmlFilePath+".e:"+e.getMessage());
        }
        return list;
    }
}